# -*- encoding=utf8 -*-
__author__ = "yingz"

import pytest
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

from utils.case_dict import casedict
from utils.send_dingmsg import dingmessage
# from airtest.cli.parser import cli_setup


# @pytest.fixture(scope='module', params=['Android://127.0.0.1:5037/UYT7N18112003639'])

failed_dict = dict()

@pytest.fixture(scope='module', params=['Android:///'])
def poco(request):
    '''
    构造新的poco，完成测试用例执行前、后的步骤
    @return: 返回新的poco对象
    '''
    connect_device(request.param)
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
    poco.device.wake()
    start_app("com.hanweb.android.sdzwfw.activity")
    sleep(8)
    yield poco
    sleep(2)
    #清除缓存
    items = poco("android.view.ViewGroup").child("android.widget.LinearLayout").offspring(
        "com.hanweb.android.sdzwfw.activity:id/main_fram").offspring(
        "com.hanweb.android.sdzwfw.activity:id/home_bottom_ll").offspring(
        "com.hanweb.android.sdzwfw.activity:id/home_tablayout").child("android.widget.LinearLayout").child(
        "android.support.v7.app.ActionBar$Tab")
    items[3].click()
    poco(name="com.hanweb.android.sdzwfw.activity:id/setting").click()
    sleep(2)
    poco(name="com.hanweb.android.sdzwfw.activity:id/tv_hcremain").click()
    sleep(2)
    poco(text="确定").click()
    sleep(3)
    stop_app("com.hanweb.android.sdzwfw.activity")
    sleep(2)

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    hook pytest失败
    :param item:
    :param call:
    :return:
    '''
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # print(outcome)
    # print(rep)

    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and (rep.failed or rep.skipped):
        # 如果跳过也重启app,因为如果标记了xfailed运行失败的话也得重启以保证不影响下个用例

        global failed_dict
        if item.name in failed_dict:
            failed_dict[item.name] = failed_dict[item.name] + 1
        else:
            failed_dict[item.name] = 1
        # print("--------------------test case is :", casedict[item.name.split('[')[0]], "failed count is", failed_dict[item.name])

        if failed_dict[item.name] == 3:
            snapshot(filename="failed" + casedict[item.name.split('[')[0]]+".png") #失败截图
            # dingmessage(tex='测试结果:'+casedict[item.name.split('[')[0]]+'异常')

        # 失败后防止影响后面的用例，关闭app再重启
        stop_app("com.hanweb.android.sdzwfw.activity")
        sleep(3)
        start_app("com.hanweb.android.sdzwfw.activity")
        sleep(8)